package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.CustomLog;
import com.ruoyi.system.domain.Dept;
import com.ruoyi.system.domain.DeptZhuanjia;
import com.ruoyi.system.domain.Zhuanjia;
import com.ruoyi.system.service.*;
import com.ruoyi.system.tools.BooleanMessage;
import com.ruoyi.web.controller.tool.JsonResult;
import com.ruoyi.web.controller.tool.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 单位信息Controller
 * 
 * @author ruoyi
 * @date 2022-12-08
 */
@Controller
@RequestMapping("/system/deptdetail")
public class DeptController extends BaseController
{
    private String prefix = "system/deptdetail";

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IZhuanjiaService zhuanjiaService;

    @Autowired
    private IDeptZhuanjiaService deptZhuanjiaService;

    @Autowired
    private ICustomLogService customLogService;

    @Autowired
    private IZhuanjiaQushiquerenService zhuanjiaQushiquerenService;

    @Autowired
    private IDeptidOlddeptidService deptidOlddeptidService;

    @RequiresPermissions("system:deptdetail:view")
    @GetMapping()
    public String deptdetail()
    {
        return prefix + "/deptdetail";
    }

    @RequiresPermissions("system:deptdetail:customview")
    @GetMapping("/customdeptdetail")
    public String customdeptdetail()
    {
        return prefix + "/customdeptdetail";
    }

//    @RequiresPermissions("system:deptdetail:customedit")
    @GetMapping("/customedit")
    public String customedit()
    {
        return prefix + "/customedit";
    }
    //单位管理-下级单位
    @GetMapping("/modaldept")
    public String modaldept(String deptid,String jigoujibie,ModelMap map)
    {
        map.put("jigoujibie",jigoujibie);
        map.put("deptid",deptid);
        return prefix + "/modal_dept";
    }
    /**
     * 查询单位信息列表
     */
    @RequiresPermissions("system:deptdetail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Dept dept)
    {
        startPage();
        List<Dept> list = deptService.selectDeptList(dept);
        return getDataTable(list);
    }

    /**
     * 查询单位信息列表custom
     */
    @RequiresPermissions("system:deptdetail:customlist")
    @PostMapping("/customlist")
    @ResponseBody
    public List<Map<String,Object>> customlist(Dept dept)
    {
        List<Map<String,Object>> list = deptService.selectDeptListCustom(dept);
        return list;
    }

    /**
     * 导出单位信息列表
     */
    @RequiresPermissions("system:deptdetail:export")
    @Log(title = "单位信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Dept dept)
    {
        List<Dept> list = deptService.selectDeptList(dept);
        ExcelUtil<Dept> util = new ExcelUtil<Dept>(Dept.class);
        return util.exportExcel(list, "单位信息数据");
    }

    /**
     * 新增单位信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存单位信息
     */
    @RequiresPermissions("system:deptdetail:add")
    @Log(title = "单位信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Dept dept)
    {
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改单位信息
     */
    @RequiresPermissions("system:deptdetail:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        Dept dept = deptService.selectDeptById(id);
        mmap.put("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 修改保存单位信息
     */
    @RequiresPermissions("system:deptdetail:edit")
    @Log(title = "单位信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Dept dept)
    {
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除单位信息
     */
    @RequiresPermissions("system:deptdetail:remove")
    @Log(title = "单位信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(deptService.deleteDeptByIds(ids));
    }

    /**
     * 查询单位信息custom
     */
    //@RequiresPermissions("system:zhuanjia:findone")
    @PostMapping("/findone")
    @ResponseBody
    public JsonResult<?> findone(@RequestParam("deptid") String ppDeptId)
    {
        try {
            Dept mmDept = deptService.selectDeptById(ppDeptId);
            return mmDept==null?JsonResult.getErrorResult("查询单位失败"):JsonResult.getSuccessResult(mmDept);
        } catch (Exception e) {
            logger.error("deptdetail -> findone: "+e.getMessage());
            return JsonResult.getErrorResult("查询单位失败");
        }
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult<?> save(Dept dept, HttpServletRequest request){
        try {
            String mmDeptId = dept.getId();

            int isOk = 0;

            if (mmDeptId==null||mmDeptId.equals("")){
                dept.setId(UUID.randomUUID().toString());
                dept.setTianjiashijian(new Date());
                dept.setZuihouxiugaishijian(new Date());
                dept.setIsvalid((long)1);

                isOk = deptService.insertDept(dept);
            }else if(mmDeptId!=null){
                dept.setZuihouxiugaishijian(new Date());

                HttpSession session = request.getSession();

                CustomLog mmLog = new CustomLog();
                mmLog.setId(UUID.randomUUID().toString());
                mmLog.setCaozuoleixing("单位信息修改");
                mmLog.setCaozuorenid(session.getAttribute("userid").toString());
                mmLog.setCaozuoren(session.getAttribute("username").toString());
                mmLog.setDanweiid(session.getAttribute("deptid").toString());
                mmLog.setDanweimingcheng(session.getAttribute("deptname").toString());
                mmLog.setCaozuoriqi(new Date());
                mmLog.setCaozuoshuoming("修改单位信息");
                mmLog.setIsvalid((long)1);

                isOk = deptService.updateDept(dept);

                //写入自定义日志
                customLogService.insertCustomLog(mmLog);
            }

            return isOk==1?JsonResult.getSuccessResult("保存成功"):JsonResult.getErrorResult("保存失败");
        } catch (Exception e) {
            logger.error("deptdetail -> findone: "+e.getMessage());
            return JsonResult.getErrorResult("查询单位失败");
        }
    }

    @PostMapping("/findvalid")
    @ResponseBody
    public JsonResult<?> findvalid(@RequestParam("deptname")String ppDeptName){
        try {
            List<Dept> mmList = new ArrayList<>();

            Dept mmDept = new Dept();
            mmDept.setJigoumingcheng(ppDeptName);

            if (ppDeptName.equals("")||ppDeptName==null){
                mmList = deptService.findCengjiAll("000");
            }else{
                mmList = deptService.selectDeptList(mmDept);
            }

            return JsonResult.getSuccessResult(mmList);
        } catch (Exception e) {
            logger.error("deptdetail -> findvalid: "+e.getMessage());
            return JsonResult.getErrorResult("查询有效单位失败");
        }
    }

    @PostMapping("/zhuxiao")
    @ResponseBody
    public JsonResult<?> zhuxiao(@RequestParam("deptid")String ppDeptId){
        try {

            Map<String,Object> mmMap = new HashMap<>();

            //这里的单位ID为旧单位ID
            Dept mmDept = deptService.selectDeptById(ppDeptId);
            if (mmDept==null){
                return JsonResult.getErrorResult("该单位不存在");
            }

            DeptZhuanjia mmDeptZhuanjia = new DeptZhuanjia();
            mmDeptZhuanjia.setDeptid(ppDeptId);
            mmDeptZhuanjia.setIsvalid((long)1);
            List<DeptZhuanjia> mmDeptZhuanjiaList = deptZhuanjiaService.selectDeptZhuanjiaList(mmDeptZhuanjia);
            if (mmDeptZhuanjiaList.size()!=0){
                mmMap.put("code","a");
                mmMap.put("msg","该单位中专家还未全部转移至其他单位，无法注销");
                return JsonResult.getSuccessResult(mmMap);
            }

            Dept mmDept2 = new Dept();
            mmDept2.setParentid(ppDeptId);
            List<Dept> mmDeptList = deptService.selectDeptList(mmDept2);
            if (mmDeptList.size()!=0){
                mmMap.put("code","b");
                mmMap.put("msg","该单位存在下属单位，无法注销");
                return JsonResult.getSuccessResult(mmMap);
            }

            mmDept.setIsvalid((long)0);
            mmDept.setZuihouxiugaishijian(new Date());
            int modifyOK = deptService.updateDept(mmDept);

            mmMap.put("code","c");
            mmMap.put("msg","注销成功");

            return modifyOK==1?JsonResult.getSuccessResult(mmMap):JsonResult.getErrorResult("注销失败");
        } catch (Exception e) {
            logger.error("deptdetail -> zhuxiao: "+e.getMessage());
            return JsonResult.getErrorResult("注销单位失败");
        }
    }

    /**
     * 检查单位必要信息是否填写
     */
    @GetMapping("/checkDeptInfo")
    @ResponseBody
    public JsonResult<?> checkDeptInfo()
    {
        try {
            BooleanMessage bm = deptService.checkDeptInfo(getUserId());
            return JsonResult.getSuccessResult(bm);
        } catch (Exception e) {
            logger.error("deptdetail -> checkDeptInfo: "+e.getMessage());
            return JsonResult.getErrorResult("检查单位必要信息是否填写失败");
        }
    }

    /**
     * 专家变动详情custom列表
     */
    @PostMapping("/bindQushiquerenDeptList")
    @ResponseBody
    public JsonResult<?> bindQushiquerenDeptList(String deptid,String danweimingcheng,int pageindex,int pagesize)
    {

        try{
            //待处理是所有下级单位和
            List<Map<String,Object>> list = deptService.bindQushiquerenDeptList(deptid,danweimingcheng);
            if(deptid.equals("0")) {
                deptid = deptidOlddeptidService.DeptIdToOldDeptId(deptid);
                list = deptService.bindQushiquerenDeptList(deptid, danweimingcheng);
            }

            //待处理是自身
            List<Map<String,Object>> selt = deptService.bindQushiquerenDeptListself(deptid,danweimingcheng);

            //待核查人员数
            for (int i = 0; i < list.size(); i++) {
                list.get(i).put("weichuli",Integer.parseInt(selt.get(i).get("weichuli").toString())+Integer.parseInt(list.get(i).get("weichuli").toString()));
            }

            list = list.stream().filter(x -> Integer.parseInt(x.get("weichuli").toString())>0).collect(Collectors.toList());

            Map<String,Integer> countinfo = zhuanjiaQushiquerenService.CountDeptandZhuanjia();
            int mmCount=0;
            mmCount = list.size();
            PageInfo mmPageInfo = new PageInfo(pageindex, pagesize, mmCount);

            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("qushiquerenDeptlist", list);
            mmMap.put("PageInfo", mmPageInfo);
            mmMap.put("deptcount", countinfo.get("deptcount"));
            mmMap.put("Renyuancount", countinfo.get("zhuanjiacount"));

            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            return JsonResult.getErrorResult(e.getMessage());
        }
    }

    /**
     * 专家管理-查询统计-账号信息查看list
     */
    @PostMapping("/Zhanghaoxinxi")
    @ResponseBody
    public JsonResult<?> Zhanghaoxinxi(String deptid)
    {
        try {
            List<Map<String,Object>> map = deptService.selectZhanghaoxinxi(deptid);
            return JsonResult.getSuccessResult(map);
        } catch (Exception e) {
            logger.error("deptdetail -> Zhanghaoxinxi: "+e.getMessage());
            return JsonResult.getErrorResult("查询专家管理-查询统计-账号信息查看list失败");
        }
    }

    //地区模糊搜索
    @PostMapping("/searchdiqu")
    @ResponseBody
    public JsonResult<?> searchdiqu(String diqu)
    {
        try {
            List<Map<String,Object>> list = deptService.searchDiqu(diqu);
            return JsonResult.getSuccessResult(list);
        } catch (Exception e) {
            logger.error("deptdetail -> searchdiqu: "+e.getMessage());
            return JsonResult.getErrorResult("搜索地区");
        }
    }
    //单位模糊搜索
    @PostMapping("/deptsearch")
    @ResponseBody
    public JsonResult<?> deptsearch(String jigoumingcheng)
    {
        try {
            List<Dept> list = deptService.deptsearch(jigoumingcheng);
            return JsonResult.getSuccessResult(list);
        } catch (Exception e) {
            logger.error("deptdetail -> searchdiqu: "+e.getMessage());
            return JsonResult.getErrorResult("搜索地区");
        }
    }
}
